const jwt = require('jsonwebtoken');
const axios = require('axios');
const NodeCache = require('node-cache');
const cache = new NodeCache();
const fs = require('fs');
const path = require('path');
const appConfig = require('./appConfig');
require("./util/logger");

// 读取配置文件
const configPath = path.join(__dirname, '../public/config.json'); // 修改路径
const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));

// 读取配置文件中的参数
const { teamId, clientId, keyId, privateKeyFile, orgId } = config;
const privateKey = fs.readFileSync(path.join(__dirname, '../public', privateKeyFile), 'utf8'); // 确保以 'utf8' 读取

/**
 * ASA 搜索广告 API 封装
 * @autor stayhau
 * @since 2024-07-09
 */
class AppleSearchAds {
    constructor(teamId, clientId, keyId, privateKey, orgId) {
        this.teamId = teamId;
        this.clientId = clientId;
        this.keyId = keyId;
        this.privateKey = privateKey;
        this.orgId = orgId;
    }

    getClientSecret() {
        let clientSecret = cache.get('clientSecret');
        if (!clientSecret) {
            clientSecret = this.createClientSecret();
            cache.set('clientSecret', clientSecret, 180 * 24 * 60 * 60); // 180 天的有效期
        }
        return clientSecret;
    }

    async getToken() {
        let token = cache.get('token');
        if (!token) {
            const clientSecret = this.getClientSecret();
            token = await this.getAsaToken(this.clientId, clientSecret);
            cache.set('token', token, 60 * 60); // 1 小时的有效期
        }
        return token;
    }

    /**
     * 创建客户端密钥
     * @returns
     */
    createClientSecret() {
        const now = Math.floor(Date.now() / 1000);
        const payload = {
            iss: this.teamId,
            iat: now,
            exp: now + 86400 * 180, //缓存 180 天
            aud: 'https://appleid.apple.com',
            sub: this.clientId
        };

        const clientSecret = jwt.sign(payload, fs.readFileSync(this.privateKey), {
            algorithm: 'ES256',
            header: {
                alg: 'ES256',
                kid: this.keyId
            }
        });

        console.log('Generated JWT:', clientSecret); // 添加日志
        return clientSecret;
    }

    /**
     * 获取访问令牌
     * @param {string} clientId
     * @param {string} clientSecret
     * @returns {Promise<string>}
     */
    async getAsaToken(clientId, clientSecret) {
        const url = 'https://appleid.apple.com/auth/oauth2/token';
        const params = new URLSearchParams();
        params.append('grant_type', 'client_credentials');
        params.append('scope', 'searchadsorg');
        params.append('client_id', clientId);
        params.append('client_secret', clientSecret);

        try {
            const response = await axios.post(url, params);
            const token = response.data.access_token;
            console.log('ASA token:', token);
            return token;
        } catch (error) {
            console.error('Error fetching ASA token:', error.response ? `Status: ${error.response.status}, Message: ${error.response.data}` : error.message);
            throw error;
        }
    }

    async fetchCampaignData(startTime, endTime, adamId) {
        const token = await this.getToken();
        const params = {
            "startTime": startTime,
            "endTime": endTime,
            "granularity": "DAILY",
            "selector": {
                "orderBy": [
                    {
                        "field": "countryOrRegion",
                        "sortOrder": "ASCENDING"
                    }
                ],
                "conditions": [
                    {
                        "field": "adamId",
                        "operator": "EQUALS",
                        "values": [adamId]
                    },
                    {
                        "field": "campaignStatus",
                        "operator": "EQUALS",
                        "values": ["ENABLED"]
                    }
                ],
                "pagination": {
                    "offset": 0,
                    "limit": 1000
                }
            },
            "groupBy": ["countryOrRegion"],
            "timeZone": "ORTZ",
            "returnRecordsWithNoMetrics": true,
            "returnRowTotals": true,
            "returnGrandTotals": true
        };

        try {
            const response = await axios.post(appConfig.REPORTS_CAMPAIGNS_URL, params, {
                headers: {
                    'Authorization': `Bearer ${token}`,
                    'X-AP-Context': `orgId=${this.orgId}`,
                    'Content-Type': 'application/json'
                }
            });
            // console.log('Campaign Data:', JSON.stringify(response.data)); // 转换为 JSON 字符串并打印
            console.log('Campaign Data:', response.data);

            // 返回结果
            return response.data;
        } catch (error) {
            console.error('Error fetching campaign data:', error.response ? `Status: ${error.response.status}, Message: ${JSON.stringify(error.response.data)}` : error.message);
            throw error; // 抛出错误
        }
    }
}

const appleSearchAds = new AppleSearchAds(teamId, clientId, keyId, privateKey, orgId);

module.exports = AppleSearchAds;